package com.prb.controller;

import com.prb.entity.Result;
import com.prb.factory.AnnotationBeanFactory;
import com.prb.service.AccountService;
import com.prb.utils.JsonUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class IndexController extends HttpServlet {

    AccountService accountService = (AccountService)AnnotationBeanFactory.getBean("accountService");

    public IndexController() throws IllegalAccessException, ClassNotFoundException, InstantiationException {
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws  IOException {

        String from = req.getParameter("fromCardNo");

        String to = req.getParameter("toCardNo");

        Integer money = Integer.parseInt(req.getParameter("money"));

        Result result = new Result();

        try {
            accountService.doTrans(from, to, money);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("500");
            result.setMessage("转账错误");
            // 响应
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().print(JsonUtils.object2Json(result));
            return ;
        }

        result.setStatus("200");
        result.setMessage("转账成功");

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));

    }
}
